//
//  Person.m
//  Runtime+NSCoding
//
//  Created by isoftstone on 2018/9/20.
//  Copyright © 2018年 isoftstone. All rights reserved.
//

#import "Person.h"
#import <objc/runtime.h>
@implementation Person

- (instancetype)initWithCoder:(NSCoder *)coder
{
    
    if (self) {
        
        unsigned int outCount;
        Ivar* ivars = class_copyIvarList([self class], &outCount);
       // objc_property_t* propertys = class_copyPropertyList([self class], &outCount);
        //NSLog(@"name_:%@",[NSString stringWithUTF8String:property_getName(propertys[0])]);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            const char* name = ivar_getName(ivar);
            NSString* objc_name = [NSString stringWithUTF8String:name];
            [self setValue:[coder decodeObjectForKey:objc_name] forKey:objc_name];
//            const char* proPerty_name = property_getName(propertys[i]);
//            NSString* objc_pro_name = [NSString stringWithUTF8String:proPerty_name];
//            const char* pro_attributes = property_getAttributes(propertys[i]);
//            NSString* objc_pro_attribute = [NSString stringWithUTF8String:pro_attributes];
           // [NSString stringWithCString:<#(nonnull const char *)#> encoding:<#(NSStringEncoding)#>]
        }
//        self.name = [coder decodeObjectForKey:@"name"];
//        self.age = [[coder decodeObjectForKey:@"age"] integerValue];
        free(ivars);
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)coder
{
    unsigned int outCount;
    Ivar* ivars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i<outCount; i++) {
        Ivar ivar = ivars[i];
        const char* name = ivar_getName(ivar);
        NSString* objc_name = [NSString stringWithUTF8String:name];
        [coder encodeObject:[self valueForKey:objc_name] forKey:objc_name];
    }
    
//    [coder encodeObject:self.name forKey:@"name"];
//    [coder encodeObject:self.age forKey:@"age"];
    free(ivars);
    
}
@end
